
import moment from 'moment'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        title:'你好呀你好呀',
        phone:'6',
        detail:'',
        price:'',
        location:'',
        prePrice:'',
        coverPic:'',
        fileList: [],
        imgList:[],
        categoryList:[],
        categoryNameList:[],
        category: 0,
        tempList:[],
        openid:'',
        pictureOne:'',
        pictureTwo:'',
        pictureThree:'',
        pictureFour:'',
        pictureFive:'',
        pictureSix:'',
        userInfo:{},
        publishInfo:{},
        goodsId:''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options)    
        
      const openid = wx.getStorageSync("openid");
      const userInfo = wx.getStorageSync("userInfo");
      this.setData({
          goodsId:options.goodsId,
         
        openid,
        userInfo,
    //     fileList:publishInfo.tempList,
    //     location:publishInfo.location,
    //    category:publishInfo.category
      })
        this.getCategoryList()
        this.getGoodsInfo()
       setTimeout(() => {
        this.getCategoryIndex()
       }, 1000);
    },
// 获取商品信息
getGoodsInfo(){
    // console.log('fff',this.data.goodsId)
    wx.request({
        url: 'http://127.0.0.1:6060/api/getGoodsInfo',
        data: {
            id:this.data.goodsId
        },
        header: {'content-type':'application/json'},
        method: 'GET',
        dataType: 'json',
        responseType: 'text',
        success: (result) => {
            console.log(result)
            const fileList = JSON.parse(result.data.message[0].fileListString)
            // console.log(result.data.message)       
           this.setData({
               publishInfo:result.data.message[0],
               fileList,
               location:result.data.message[0].location
           })
        },  
    });
},
getCategoryIndex(){
    const category = this.data.categoryNameList.findIndex(v=>{
        return v == this.data.publishInfo.category
    })
    this.setData({
        category
    })
},
    //获取详细地址
    chooseLocation(){
        
        wx.chooseLocation({
            success:res=>{
              this.setData({
                  location:res.address
              })
            }
        })
    },

  //图片预览
    previewImg: function(event) {
      
        var src = event.detail.url; 
        var imgList = []; 
        const {
          fileList = []
        } = this.data
        fileList.forEach((item, index, fileList) => {
          imgList.push(item.url);
        })
        //图片预览
        wx.previewImage({
          current: src, // 当前显示图片的http链接
          urls: imgList // 需要预览的图片http链接列表
          
        })
      },
    
    
      //删除图片
      deleteToCloud: function(event) {
        
        let fileID = event.detail.file.url
        let index = event.detail.index
        let fileList_new = this.data.fileList
        let imgList_new = this.data.imgList
        wx.showLoading({
          title: '正在删除',
        });
        wx.cloud.deleteFile({
          fileList: [fileID],
          success: res => {
            console.log("图片删除成功", res)
            fileList_new.splice(index, 1);
            imgList_new.splice(index, 1);
            wx.hideLoading();
            wx.showToast({
              icon: 'success',
              title: '删除成功'
            })
            this.setData({
              fileList: fileList_new,
              imgList: imgList_new
            })
          },
          fail: err => {
            wx.hideLoading();
            wx.showToast({
              icon: 'none',
              title: '删除失败'
            })
            console.log(err)
          }
        })
      },
    
    
    //上传图片到云存储
      uploadToCloud: function(event) {
      
        const {
          fileList = []
        } = this.data
       const {
         imgList = []
       } = this.data
    
        const {
          file
        } = event.detail
       
        file.forEach((item, index, file) => {
          
          wx.showLoading({
            title: '正在提交',
          });
          wx.cloud.uploadFile({
            cloudPath: `goods/${(new Date()).getTime() + Math.floor(9 * Math.random())}` + ".jpg", // 上传至云端的路径
            filePath: item.path, // 小程序临时文件路径
            success: res => {
              // 返回文件 ID
              fileList.push({
                url: res.fileID
              });
              imgList.push(res.fileID)             
              this.setData({
                fileList,
               imgList
              });
              wx.hideLoading();
            },
            fail: function() {
              wx.hideLoading();
              console.error
            }
          })
        });
      },
    
  
    // 选择分类
    bindPickerChange: function(e) {
        // console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
          category: Number(e.detail.value)
        })
      },

getUrl(){
  console.log(this.data.imgList)
  wx.cloud.getTempFileURL({
    fileList: this.data.imgList,
    success: res => {
      // get temp file URL
      console.log(res.fileList)
    },
    fail: err => {
      // handle error
    }
  })
},


      publich(event){
   
          //从云存储获取封面
          wx.cloud.getTempFileURL({
            fileList: this.data.imgList, 
            success: res => {
                
             
              this.setData({
                coverPic:res.fileList[0].tempFileURL,
               tempList:res.fileList               
            })
            wx.showLoading({
              title: '正在发布',
              mask:true
            });

            wx.request({
              
              url: 'http://127.0.0.1:6060/api/updateGoods',
              header: {"Content-Type": "application/json; charset=utf-8"},
              method: 'post',
              data:{
                goodsId:this.data.goodsId,
                coverPic:this.data.coverPic,
                  location:this.data.location,
                  phone: event.detail.value.phone,
                  price: event.detail.value.price,
                  detail: event.detail.value.detail,
                  prePrice: event.detail.value.prePrice,
                  title: event.detail.value.title,
                  fileListString:JSON.stringify(this.data.fileList),
                  category:this.data.categoryNameList[this.data.category],
                //   time:moment().format('YY-MM-DD HH:mm:ss'),
                  tempList:this.data.tempList
                  
              },
              success: (result) => {
                  console.log(result)
               console.log('会跳转')
               
                  wx.navigateTo({
                    url: '/pages/myPublish/myPublish',
                    
                  });
                    
               },
               fail: err => {
                console.log('不会跳转',err)
              }
          })
            


            },
            fail: err => {
              console.log('失败了',err)
            }
          })
        
            // wx.cloud.getTempFileURL({
            //     fileList: ({
            //       fileID:this.data.imgList,
            //       //  fileID:this.data.fileList[0].url,
            //     //   maxAge: 60 * 60, // one hour
            //     })
            //   }).then(res => {
            //     console.log(res.fileList)
            //     this.setData({
            //         coverPic:res.fileList[0].tempFileURL
            //     })

            //     // 将商品数据插入到数据库里
            //     wx.request({
            //         url: 'http://127.0.0.1:6060/api/addGoods',
            //         header: {"Content-Type": "application/x-www-form-urlencoded"},
            //         method: 'post',
            //         data:{
            //             coverPic:this.data.coverPic,
            //             location:this.data.location,
            //             phone: event.detail.value.phone,
            //             price: event.detail.value.price,
            //             detail: event.detail.value.detail,
            //             prePrice: event.detail.value.prePrice,
            //             title: event.detail.value.title,
            //             category:this.data.categoryNameList[this.data.category],
            //             time:moment().format('YY-MM-DD HH:mm:ss')
            //         },
            //         success: (result) => {
            //             console.log(result)
            //             }
            //     })
            //   }).catch(error => {
            //     wx.showToast({
            //         icon: 'none',
            //         title: '发布失败,请稍后再试'
            //       })
            //   })
         
    },



    // 获取分类
    getCategoryList(){
        wx.request({
            url: 'http://127.0.0.1:6060/api/getCategoryList',
            header: {'content-type':'application/json'},
            method: 'GET',
            dataType: 'json',
            success: (result) => {
                const categoryList = result.data.data
                const categoryNameList = ['其他']
                categoryList.forEach(v => {
                    categoryNameList.push(v.categoryName)
                });
                // console.log(categoryNameList)
                this.setData({
                    categoryList,
                    categoryNameList
                })
            },
            
        });
    },
   
   
})



